/*
 * Copyright 2010 Biz-e (info@biz-e.nl)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.biz_e.site.client;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Image;

/**
 * Simple clickable image that switches images depending on selected state 
 * 
 * @author Joost A. Bloemsma
 */
public class MyButton extends Image implements ClickHandler {
    private String id;
    private MyButtonListener listener;
    private boolean selected = false;

    /**
     * Constructs a new MyButton instance
     * @param id The id that isentifies the images and the content to display 
     * @param listener The MyButtonListener that listens to this button
     */
    public MyButton(String id, MyButtonListener listener) {
        super("/img/btn_" + id + ".png");
        this.id = id;
        this.listener = listener;
        this.addClickHandler(this);
    }

    /**
     * @return The id of this button (The id of the text to show)
     */
    public String getId() {
        return id;
    }

    /**
     * Sets the button to (un)selected mode depending on the passed boolean.
     * @param selected Set to true to select selected mode
     */
    public void setSelected(boolean selected) {
        this.selected = selected;
        if (selected) {
            this.setUrl("/img/btn_" + id + "_selected.png");
        } else {
            this.setUrl("/img/btn_" + id + ".png");
        }
    }

    /**
     * Checks if this button is selected (active)
     * @return true if selected
     */
    public boolean isSelected() {
        return this.selected;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onClick(ClickEvent event) {
        if (listener != null) {
            listener.onClick(this);
        }
    }

    /**
     * A listener that listens to the onClick event of the Image
     * @author Joost A. Bloemsma
     *
     */
    public static interface MyButtonListener {
        /**
         * Gets fired whenever the image of this button is clicked.
         * @param source A reference to the clicked button
         */
        public void onClick(MyButton source);
    }

}
